package com.xx.library.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.xx.library.common.Result;
import com.xx.library.entity.Book;
import com.xx.library.service.BookService;
import com.xx.library.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.text.SimpleDateFormat;

@RestController
//所有接口路径以/api/books开头
@RequestMapping("/api/books")
public class BookController {

    @Value("${upload.path}")
    private String uploadPath;

    @Autowired
    private BookService bookService;

    @GetMapping("/{id}")
    public Result<Book> getBookById(@PathVariable Long id) {
        return Result.success(bookService.getBookById(id));
    }

    @GetMapping("/isbn/{isbn}")
    public Result<Book> getBookByIsbn(@PathVariable String isbn) {
        return Result.success(bookService.getBookByIsbn(isbn));
    }

    @GetMapping
    public Result<List<Book>> getAllBooks() {
        return Result.success(bookService.getAllBooks());
    }

    @GetMapping("/search")
    public Result<List<Book>> searchBooks(Book book) {
        return Result.success(bookService.getBooksByCondition(book));
    }

    //  添加图书
    @PostMapping
    public Result<Void> addBook(@RequestParam("coverImage") MultipartFile coverImage, @RequestParam("book") String bookJson) throws IOException {
        // 将JSON字符串转换为Book对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册Java 8日期模块
        objectMapper.registerModule(new JavaTimeModule());
        Book book = objectMapper.readValue(bookJson, Book.class);
        
        // 处理封面图片上传
        if (coverImage != null && !coverImage.isEmpty()) {
            String uploadDir = uploadPath + "/books";
            String fileName = FileUtil.uploadFile(coverImage, uploadDir);
            File file = new File(fileName);
            String coverFileName = file.getName();
            System.out.println(coverFileName);
            book.setCoverImage(coverFileName);
        }
        
        bookService.addBook(book);
        return Result.success();
    }

    @PutMapping
    public Result<Void> updateBook(@RequestParam(value = "coverImage", required = false) MultipartFile coverImage, @RequestParam("book") String bookJson) throws IOException {
        // 将JSON字符串转换为Book对象
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        Book book = objectMapper.readValue(bookJson, Book.class);
        
        // 处理封面图片上传
        if (coverImage != null && !coverImage.isEmpty()) {
            String uploadDir = uploadPath + "/books";
            String fileName = FileUtil.uploadFile(coverImage, uploadDir);
            File file = new File(fileName);
            String coverFileName = file.getName();
            book.setCoverImage(coverFileName);
        }
        
        bookService.updateBook(book);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return Result.success();
    }


    // 获取封面图片
    @GetMapping("/cover/{coverImage}")
    public ResponseEntity<Resource> getCoverImage(@PathVariable String coverImage) {
        try {
            Path imagePath = Paths.get(uploadPath, "books", coverImage);
            Resource resource = new UrlResource(imagePath.toUri());
            
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/search/title")
    public Result<List<Book>> searchBooksByTitle(@RequestParam String title) {
        return Result.success(bookService.searchBooksByTitle(title));
    }
} 